// 分数管理器
export class ScoreManager {
    constructor() {
        this.score = 0;
        this.time = 0;
        this.combo = 0;
        this.timer = null;
        this.timerCallback = null;
        this.isPaused = false;
        this.startTime = null;
        this.pausedTime = 0;
    }

    // 计算分数
    calculateScore(matchLength, combo = 1) {
        // 基础分数：每个消除的小鬼10分
        let baseScore = matchLength * 10;

        // 长度奖励：超过3个的额外奖励
        if (matchLength > 3) {
            baseScore += (matchLength - 3) * 20;
        }

        // 连击倍数
        let comboMultiplier = 1;
        if (combo > 1) {
            comboMultiplier = 1 + (combo - 1) * 0.5; // 每次连击增加50%
        }

        // 计算最终分数
        const finalScore = Math.floor(baseScore * comboMultiplier);

        console.log(`分数计算: 基础${baseScore} × 连击${comboMultiplier.toFixed(1)} = ${finalScore}`);
        
        return finalScore;
    }

    // 获取匹配长度的奖励分数
    getLengthBonus(matchLength) {
        const bonuses = {
            3: 0,      // 3连无奖励
            4: 50,     // 4连奖励50分
            5: 100,    // 5连奖励100分
            6: 200,    // 6连奖励200分
            7: 400,    // 7连奖励400分
            8: 800     // 8连奖励800分
        };

        return bonuses[matchLength] || (matchLength > 8 ? 1000 : 0);
    }

    // 获取连击奖励分数
    getComboBonus(combo) {
        if (combo <= 1) return 0;
        
        // 连击奖励：2连击100分，之后每连击增加100分
        return (combo - 1) * 100;
    }

    // 计算详细分数（包含各种奖励）
    calculateDetailedScore(matches, combo = 1) {
        let totalScore = 0;
        let details = {
            baseScore: 0,
            lengthBonus: 0,
            comboBonus: 0,
            comboMultiplier: 1,
            totalMatches: 0
        };

        // 计算所有匹配的基础分数
        matches.forEach(match => {
            const matchLength = match.cells.length;
            details.totalMatches += matchLength;
            
            // 基础分数
            const basePoints = matchLength * 10;
            details.baseScore += basePoints;
            
            // 长度奖励
            const lengthBonus = this.getLengthBonus(matchLength);
            details.lengthBonus += lengthBonus;
        });

        // 连击倍数
        if (combo > 1) {
            details.comboMultiplier = 1 + (combo - 1) * 0.5;
            details.comboBonus = this.getComboBonus(combo);
        }

        // 计算总分
        totalScore = Math.floor((details.baseScore + details.lengthBonus) * details.comboMultiplier) + details.comboBonus;

        console.log('详细分数计算:', details);
        
        return {
            score: totalScore,
            details: details
        };
    }

    // 开始计时
    startTimer(callback) {
        this.timerCallback = callback;
        this.startTime = Date.now();
        this.time = 0;
        this.pausedTime = 0;
        this.isPaused = false;

        this.timer = setInterval(() => {
            if (!this.isPaused) {
                const elapsed = Math.floor((Date.now() - this.startTime - this.pausedTime) / 1000);
                this.time = elapsed;
                
                if (this.timerCallback) {
                    this.timerCallback(this.time);
                }
            }
        }, 1000);

        console.log('计时器开始');
    }

    // 暂停计时
    pauseTimer() {
        if (!this.isPaused && this.timer) {
            this.isPaused = true;
            this.pauseStartTime = Date.now();
            console.log('计时器暂停');
        }
    }

    // 恢复计时
    resumeTimer() {
        if (this.isPaused && this.timer) {
            this.pausedTime += Date.now() - this.pauseStartTime;
            this.isPaused = false;
            console.log('计时器恢复');
        }
    }

    // 停止计时
    stopTimer() {
        if (this.timer) {
            clearInterval(this.timer);
            this.timer = null;
            this.timerCallback = null;
            console.log('计时器停止');
        }
    }

    // 重置分数管理器
    reset() {
        this.stopTimer();
        this.score = 0;
        this.time = 0;
        this.combo = 0;
        this.isPaused = false;
        this.startTime = null;
        this.pausedTime = 0;
        console.log('分数管理器重置');
    }

    // 格式化时间显示
    formatTime(seconds) {
        const minutes = Math.floor(seconds / 60);
        const remainingSeconds = seconds % 60;
        return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
    }

    // 获取当前分数
    getScore() {
        return this.score;
    }

    // 获取当前时间
    getTime() {
        return this.time;
    }

    // 获取格式化的时间
    getFormattedTime() {
        return this.formatTime(this.time);
    }

    // 添加分数
    addScore(points) {
        this.score += points;
        return this.score;
    }

    // 设置分数
    setScore(score) {
        this.score = score;
        return this.score;
    }

    // 获取游戏统计信息
    getGameStats() {
        return {
            score: this.score,
            time: this.time,
            formattedTime: this.getFormattedTime(),
            averageScorePerMinute: this.time > 0 ? Math.floor((this.score / this.time) * 60) : 0
        };
    }

    // 检查是否创造新纪录（需要本地存储支持）
    checkHighScore() {
        const currentHighScore = this.getHighScore();
        if (this.score > currentHighScore) {
            this.setHighScore(this.score);
            return true;
        }
        return false;
    }

    // 获取最高分（从本地存储）
    getHighScore() {
        try {
            return parseInt(localStorage.getItem('ghostMatchHighScore') || '0');
        } catch (error) {
            console.warn('无法读取最高分:', error);
            return 0;
        }
    }

    // 设置最高分（保存到本地存储）
    setHighScore(score) {
        try {
            localStorage.setItem('ghostMatchHighScore', score.toString());
            console.log('新纪录保存:', score);
        } catch (error) {
            console.warn('无法保存最高分:', error);
        }
    }
}